<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\admin\model\UserPoints as UserPointsModel;
use think\Request;
use think\Validate;

/**
 * 用户积分接口
 */
class UserPoints extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 获取用户积分汇总
     */
    public function getPointsSummary()
    {
        $user = $this->auth->getUser(true);
        $userId = $user ? $user['uid'] : 1; // 修复：使用uid字段而不是id字段
        
        $summary = UserPointsModel::getUserPointsSummary($userId);
        
        return json([
            'code' => 200,
            'data' => $summary,
            'msg' => '获取成功'
        ]);
    }

    /**
     * 获取用户积分记录列表
     */
    public function getPointsList()
    {
        $user = $this->auth->getUser(true);
        $userId = $user ? $user['uid'] : 1; // 修复：使用uid字段而不是id字段

        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);

        $result = UserPointsModel::getUserPoints($userId, $page, $limit);
        
        return json([
            'code' => 200,
            'data' => $result,
            'msg' => '获取成功'
        ]);
    }

    /**
     * 添加积分（管理员功能）
     */
    public function addPoints()
    {
        $user = $this->auth->getUser(true);
        // 测试时允许不登录

        $data = input('post.');
        
        // 验证数据
        $validate = new Validate();
        $validate->rule([
            'user_id' => 'require|integer',
            'points' => 'require|integer',
            'source' => 'require',
            'description' => 'max:255'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        $result = UserPointsModel::addPoints(
            $data['user_id'],
            $data['points'],
            $data['source'] ?? 'admin_reward',
            $data['source_id'] ?? 0,
            $data['description'] ?? ''
        );

        if ($result) {
            return json(['code' => 200, 'msg' => '积分添加成功']);
        } else {
            return json(['code' => 500, 'msg' => '积分添加失败']);
        }
    }

    /**
     * 每日答题奖励积分
     */
    public function dailyQuestionReward()
    {
        $user = $this->auth->getUser(true);
        if (!$user) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        // 检查今日是否已获得答题积分
        $hasReward = UserPointsModel::checkTodayPoints($user['uid'], 'daily_question');
        if ($hasReward) {
            return json(['code' => 400, 'msg' => '今日已获得答题积分']);
        }

        $questionId = input('question_id', 0, 'intval');
        $result = UserPointsModel::addPoints(
            $user['uid'],
            3,
            'daily_question',
            $questionId,
            '每日答题正确奖励'
        );

        if ($result) {
            return json([
                'code' => 200,
                'data' => ['points' => 3],
                'msg' => '恭喜您获得3积分！'
            ]);
        } else {
            return json(['code' => 500, 'msg' => '积分奖励失败']);
        }
    }

    /**
     * 检查今日答题状态
     */
    public function checkTodayStatus()
    {
        $user = $this->auth->getUser(true);
        if (!$user) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        $hasAnswered = UserPointsModel::checkTodayPoints($user['uid'], 'daily_question');
        $summary = UserPointsModel::getUserPointsSummary($user['uid']);
        
        return json([
            'code' => 200,
            'data' => [
                'has_answered_today' => $hasAnswered,
                'today_points' => $summary['today_points'],
                'total_points' => $summary['total_points']
            ],
            'msg' => '获取成功'
        ]);
    }

    /**
     * 获取积分来源列表
     */
    public function getSourceList()
    {
        $model = new UserPointsModel();
        $sourceList = $model->getSourceList();
        
        return json([
            'code' => 200,
            'data' => $sourceList,
            'msg' => '获取成功'
        ]);
    }
}